package com.cheng.student.controller.servlet;

import com.cheng.student.beans.Administrator;
import com.cheng.student.service.AdministratorServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "ChangeSuperServlet", value = "/super/ChangeSuperServlet")
public class ChangeSuperServlet
        extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");


        //校验
        if (oldPassword == null || "".equals(oldPassword))
        {
            response.getWriter().write("请输入旧密码");
            return;
        }
        if(newPassword == null || "".equals(newPassword))
        {
            response.getWriter().write("请输入新密码");
            return;
        }

        //通过
        Administrator administrator = ((Administrator) request.getSession().getAttribute("administrator"));
        String password = administrator.getPassword();


        if(!password.equals(oldPassword))
        {
            response.getWriter().write("旧密码错误");
            return;
        }


        AdministratorServiceImpl administratorService = new AdministratorServiceImpl();

        try
        {
            int i = administratorService.changePassword(administrator.getUsername()
                    , administrator.getPassword()
                    , newPassword);
            System.out.println(i);
            if(i != 1)
            {
                throw new Exception();
            }
        }
        catch (Exception exception)
        {
            response.getWriter().write("未知错误，更改失败");
            return;
        }

        response.getWriter().write("更改成功，恭喜你");

        //清除登录信息
        request.getSession().removeAttribute("power");
        request.getSession().removeAttribute("administrator");
    }
}
